package com.north.light.libpicblur;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.View;
import android.widget.FrameLayout;

import java.io.Serializable;

/**
 * Created by lzt
 * time 2020/10/27
 * 描述：控件工具类
 */
public class LibPicBlurViewShotUtils implements Serializable {

    /**
     * 对View进行截图
     */
    public interface ViewSnapListener {
        void success(Bitmap bitmap);

        void failed(String message);
    }


    /**
     * 普通截图
     */
    public static void viewSnapShot(View view, ViewSnapListener listener) {
        try {
            //使控件可以进行缓存
            view.setDrawingCacheEnabled(true);
            //获取缓存的 Bitmap
            Bitmap drawingCache = view.getDrawingCache();
            //复制获取的 Bitmap
            drawingCache = Bitmap.createBitmap(drawingCache, 0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
            //关闭视图的缓存
            view.setDrawingCacheEnabled(false);
            view.destroyDrawingCache();
            if (drawingCache != null) {
                if (listener != null) {
                    listener.success(drawingCache);
                }
            } else {
                if (listener != null) {
                    listener.failed("draw cache is null");
                }
            }
        } catch (Exception e) {
            if (listener != null) {
                listener.failed(e.getMessage());
            }
        }
    }

    /**
     * FrameLayout截图
     * 可用于scroll view截图
     */
    public static void viewSnapShot(FrameLayout scrollParent, ViewSnapListener listener) {
        try {
            int h = 0;
            Bitmap bitmap;
            // 获取listView实际高度
            for (int i = 0; i < scrollParent.getChildCount(); i++) {
                h += scrollParent.getChildAt(i).getHeight();
            }
            // 创建对应大小的bitmap
            bitmap = Bitmap.createBitmap(scrollParent.getWidth(), h, Bitmap.Config.ARGB_8888);
            final Canvas canvas = new Canvas(bitmap);
            scrollParent.draw(canvas);
            if (listener != null) {
                listener.success(bitmap);
            }
        } catch (Exception e) {
            if (listener != null) {
                listener.failed(e.getMessage());
            }
        }
    }
}
